package com.martin.fastframe.ui.blood.strip

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.RelativeLayout
import androidx.databinding.DataBindingUtil
import com.martin.fastframe.R
import com.martin.fastframe.databinding.ViewBloodStripBinding
import com.martin.lib_base.ktx.loge
import com.xuexiang.xui.utils.DensityUtils
import dev.utils.app.ViewUtils

class BloodStripView : FrameLayout {

    //视图绑定器
    private var binding: ViewBloodStripBinding? = null

    //左侧数值
    var leftNumber: Int = 0
        set(value) {
            field = value
            refreshUI()
        }

    //右侧数值
    var rightNumber: Int = 0
        set(value) {
            field = value
            refreshUI()
        }

    //两边的固定宽度
    private val fixedWidth = DensityUtils.dp2px(context, 50f)

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init()
    }

    private fun init() {
        if (binding == null) {
            binding = DataBindingUtil.inflate(
                LayoutInflater.from(context),
                R.layout.view_blood_strip,
                this,
                true
            )
        }

        refreshUI()
    }

    private fun refreshUI() {
        post {
            binding?.apply {
                //比例条宽度
                val progressWidth = measuredWidth - (fixedWidth * 2)
                loge("刷新UI : measuredWidth=$measuredWidth ; progressWidth=$progressWidth ; fixedWidth=$fixedWidth")
                val rightWidth: Int
                val leftWidth: Int
                //如果两边数值都为0,则直接分配为
                val total = leftNumber + rightNumber
                if (total == 0) {
                    rightWidth = (progressWidth / 2) + fixedWidth
                    leftWidth = measuredWidth - rightWidth
                } else {
                    rightWidth = (1f * progressWidth * rightNumber / total).toInt() + fixedWidth
                    leftWidth = measuredWidth - rightWidth
                }
                loge("刷新UI : leftWidth=$leftWidth ; rightWidth=$rightWidth")

                //设置血条
                ViewUtils.setWidth(vBloodRight, leftWidth)
                ViewUtils.setWidth(vBloodRight, rightWidth)
                //设置图片位置
                val params = ivPoint.layoutParams as RelativeLayout.LayoutParams
                params.marginStart = leftWidth - DensityUtils.dp2px(context, 15f)
                ivPoint.layoutParams = params

                tvLeft.text = leftNumber.toString()
                tvRight.text = rightNumber.toString()
            }
        }
    }

}